<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $nav = $this->get_nav();
        $goods_list = D('goods')->get_index_goods();

        $user_id = is_login();
        if($user_id) {
            $drawer_list = D('drawer')->get_user_drawer_list($user_id, 'id, title');
            $this->assign('drawer_list', $drawer_list);
        }


        $this->assign('goods_list', $goods_list);
        $this->assign('nav_list', $nav);
        $this->display('index');
    }

    public function discover() {
    	echo "登录成功";
    }

    /**
     * 获得验证码
     */
    public function get_code(){
        $config=array(
            'fontSize'	=>30,
            'length'    =>4,
            'useNoise'  =>false,
        );
        $Verify= new \Think\Verify($config);
        $Verify->entry(1);
    }


    /**
     * 获取导航数据, 将导航数据写入memcache
     */
    private function get_nav() {
        $cate_model = M('category');
        $cate_data = $cate_model->order('cate_path')->select();
        return $this->get_category($cate_data, 0, 2);
    }

    /**
     * 获取导航无限极分类信息
     * @param $data 数据库中存放的分类数据
     * @param $pid  父级id
     * @param $layer 层级，表示要从中遍历出多少层的分类数据 1表示只取一层
     */
    private function get_category($data=array(), $pid=0, $layer)
    {
        $result = array();
        static $loop_count = 0;
        if($loop_count == $layer) return $result;

        foreach($data as $k=>$v) {
            if($v['pid'] == $pid) {
                //只有获取的数据超过一层的时候采取获取下层的数据
                if($layer > 1) {
                    $v[child] = $this->get_category($data, $v['id'], $loop_count+1);
                }
                $result[] = $v;
            }
        }
        $loop_count++;
        return $result;
    }
}